<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User_model extends CI_Model {
	function __construct() {
		parent::__construct();
		$this->load->database();
	}
	public function add_new_user($birthday, $phone_number, $requestID) {
		$data = array('phone_number'=>$phone_number,
				'birthday' => $birthday,
				'requestID' => $requestID,
				'active' => 0);
		// 		var_dump($data); die();

		$this->db->insert('tbl_user',$data);

		return $this->db->insert_id();
	}
	public function getUserByRequestID($requestId) {
		$this->db->where('requestId', $requestId);
		$query = $this->db->get('tbl_user');
		if($query->num_rows() > 0){
			$array = $query->result();
			return $array[0];
		}else{
			return null;
		}
	}
	public function getUserByID($id) {
		$this->db->where('id', $id);
		$query = $this->db->get('tbl_user');
		if($query->num_rows() > 0){
			$array = $query->result();
			return $array[0];
		}else{
			return null;
		}
	}
	public function activeUser($id, $otp) {
		$this->db->update('tbl_user', array('active' => 0, 'verify_code'=>$otp), "id = ".$id);
	}
	public function getUserByPhoneNumber($phone_number) {
		$this->db->where('phone_number', $phone_number);
		$this->db->order_by('id','desc');
		$this->db->limit(1);
		$query = $this->db->get('tbl_user');
		if($query->num_rows() > 0){
			$array = $query->result();
			return $array[0];
		}else{
			return null;
		}
	}
	public function deactiveUserByUserId($id) {
		$this->db->update('tbl_user', array('active' => 0), "id = ".$id);
	}
	public function activeUserByUserId($id) {
		$this->db->update('tbl_user', array('active' => 1), "id = ".$id);
	}
	public function deactiveUserByPhoneNumber($phone_number) {
		$user = $this->getUserByPhoneNumber($phone_number);
		if ($user) {
			$this->deactiveUserByUserId($user->id);
		}
		else {
			return null;
		}
	}
	public function activeUserByPhoneNumber($phone_number) {
		$user = $this->getUserByPhoneNumber($phone_number);
		if ($user) {
			$this->activeUserByUserId($user->id);
		}
		else {
			return null;
		}
	}
	public function sentSMS($id) {
		$this->db->update('tbl_user', array('is_sent_sms' => 1), "id = ".$id);
	}
	public function resetSMS() {
		$this->db->update('tbl_user', array('is_sent_sms' => 0), "active = 1");
	}
	public function getTop2Users($id) {
		$this->db->limit(2);
		$this->db->where('id >',$id);
		$this->db->where('active',1);
		$this->db->order_by('id','asc');
		$query = $this->db->get('tbl_user');
		if($query->num_rows() > 0){
			return $query->result();
		}else {
			return array();
		}
	}
}